<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button @click="searchFilter">查询</el-button></div>
    <table-render ref="table" :config="tableOption" />
  </div>
</template>
<script>
import TableRender from '@/components/Render/tableRender'
import { VueTable } from '@/components/Render/vueTable'
import { fetchList } from '@/api/article'
import { parseTime } from '@/utils'

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'AdaptiveTable',
  components: { TableRender },
  data() {
    const tableOption = VueTable.tools.getOption()
    tableOption.table.searchArgs = {
      arg1: '',
      arg2: ''
    }
    tableOption.table.cols = [
      { label: 'ID', name: 'id' },
      { label: 'Date', name: 'timestamp', formatter: val => parseTime(val, '{y}-{m}-{d} {h}:{i}') },
      {
        label: 'Title', name: 'title', align: 'left', render: (createElement, row, value) => {
          const type = row['type']
          const typeFilter = (val) => calendarTypeKeyValue[val]

          return createElement(
            'div',
            [
              createElement('span', { class: 'link-type', on: { click: () => { alert('click title') } }}, [value]),
              createElement('el-tag', [typeFilter(type)])
            ]
          )
        }
      },
      { label: 'Author', name: 'author' },
      { label: 'Reviewer', name: 'reviewer' },
      { label: 'Imp', name: 'importance' },
      { label: 'Readings', name: 'pageviews' },
      { label: 'Status', name: 'status' }
    ]
    tableOption.table.searching = (args, isAll, bindTable) => {
      fetchList().then(response => {
        setTimeout(() => {
          bindTable({
            list: response.data.items,
            total: response.data.total
          })
        }, 1500)
      })
    }
    const btnEdit = VueTable.tools.operation.default({ text: '编辑' }, (row) => {
      alert('编辑')
    })
    const btnDelete = VueTable.tools.operation.default({ text: '删除' }, (row) => {
      alert('删除')
    })
    tableOption.table.operation = [btnEdit, btnDelete]

    return {
      tableOption: tableOption
    }
  },
  mounted() {
    this.searchFilter()
  },
  methods: {
    searchFilter() {
      this.$refs['table'].searchFilter()
    }
  }
}
</script>
